const Banner = require('../models/Banner');

/**
 * 获取前端轮播图列表
 * GET /api/banners
 */
exports.getBanners = async (req, res, next) => {
  try {
    const { platform = 'mobile', limit = 10 } = req.query;

    // 获取有效的轮播图
    const banners = await Banner.getActiveBanners(platform, parseInt(limit));

    // 转换为前端需要的格式
    const formattedBanners = banners.map(banner => ({
      id: banner._id.toString(),
      title: banner.title,
      image: banner.image,
      link: banner.link,
      linkType: banner.linkType,
      linkTarget: banner.linkTarget,
      description: banner.description
    }));

    res.json(formattedBanners);
  } catch (error) {
    console.error('获取轮播图失败:', error);
    
    // 返回默认轮播图，避免前端报错
    const defaultBanners = [
      {
        id: 'default1',
        title: '欢迎来到Trove商城',
        image: 'https://via.placeholder.com/800x400/FF6900/FFFFFF?text=Trove商城',
        link: '',
        linkType: 'none',
        linkTarget: '',
        description: '欢迎来到Trove商城'
      },
      {
        id: 'default2',
        title: '精选好物',
        image: 'https://via.placeholder.com/800x400/1976D2/FFFFFF?text=精选好物',
        link: '',
        linkType: 'none',
        linkTarget: '',
        description: '精选好物推荐'
      }
    ];
    
    res.json(defaultBanners);
  }
};

/**
 * 记录轮播图点击
 * POST /api/banners/:id/click
 */
exports.recordClick = async (req, res, next) => {
  try {
    const { id } = req.params;

    // 验证ID格式
    if (!id || id === 'default1' || id === 'default2') {
      return res.json({ success: true, message: '默认轮播图，无需记录点击' });
    }

    const banner = await Banner.findById(id);
    if (!banner) {
      return res.status(404).json({
        success: false,
        message: '轮播图不存在'
      });
    }

    // 增加点击次数
    await banner.incrementClick();

    res.json({
      success: true,
      message: '点击记录成功',
      clickCount: banner.clickCount + 1
    });
  } catch (error) {
    console.error('记录轮播图点击失败:', error);
    // 点击统计失败不影响用户体验，返回成功
    res.json({ success: true, message: '点击记录完成' });
  }
};

/**
 * 获取轮播图统计信息
 * GET /api/banners/stats
 */
exports.getBannerStats = async (req, res, next) => {
  try {
    const { startDate, endDate } = req.query;

    // 构建时间查询条件
    const dateQuery = {};
    if (startDate) {
      dateQuery.createdAt = { $gte: new Date(startDate) };
    }
    if (endDate) {
      dateQuery.createdAt = { 
        ...dateQuery.createdAt,
        $lte: new Date(endDate) 
      };
    }

    // 获取统计数据
    const [
      totalBanners,
      activeBanners,
      totalClicks,
      platformStats
    ] = await Promise.all([
      Banner.countDocuments(dateQuery),
      Banner.countDocuments({ ...dateQuery, isActive: true }),
      Banner.aggregate([
        { $match: dateQuery },
        { $group: { _id: null, totalClicks: { $sum: '$clickCount' } } }
      ]),
      Banner.aggregate([
        { $match: dateQuery },
        { 
          $group: { 
            _id: '$platform', 
            count: { $sum: 1 },
            clicks: { $sum: '$clickCount' }
          } 
        }
      ])
    ]);

    res.json({
      success: true,
      data: {
        totalBanners,
        activeBanners,
        inactiveBanners: totalBanners - activeBanners,
        totalClicks: totalClicks[0]?.totalClicks || 0,
        platformStats: platformStats.reduce((acc, stat) => {
          acc[stat._id] = {
            count: stat.count,
            clicks: stat.clicks
          };
          return acc;
        }, {})
      }
    });
  } catch (error) {
    console.error('获取轮播图统计失败:', error);
    next(error);
  }
};
